#!/bin/bash
set -xeuo pipefail
# See docs in cmd-offline-update.  This bit of code is run inside
# a supermin VM; the cmd-offline-update is run outside.

echo "mounting disks"
sysroot=/mnt
mkdir -p "${sysroot}"
rootdev=/dev/disk/by-label/root
bootdev=/dev/disk/by-label/boot
mount "$rootdev" "${sysroot}"
mount "$bootdev" "${sysroot}/boot"

repo=$1
shift
ref=$1
shift
no_undeploy=$1
shift

set -x
ostree pull-local --repo="${sysroot}"/ostree/repo "${repo}" "${ref}"
# shellcheck disable=SC2012
stateroot=$(basename "$(ls -d "${sysroot}/ostree/deploy/"* | head -1)")
# zipl needs special casing
bootloader='unset'
if grep -q bootloader=zipl "${sysroot}"/ostree/repo/config; then
    bootloader=zipl
    # Temporarily undo zipl, we take care of it manually
    sed -i -e 's,bootloader=zipl,bootloader=none,' "${sysroot}"/ostree/repo/config
else
    if grep -q bootloader=none "${sysroot}"/ostree/repo/config; then
        bootloader=none
    fi
fi

# HACK for old systems that use grub2-mkconfig
if [ "${bootloader}" = "unset" ]; then
    cat >/usr/bin/dummy-mkconfig << 'EOF'
    exec touch $2
EOF
    chmod a+x /usr/bin/dummy-mkconfig
fi
env OSTREE_DEBUG_GRUB2=1 OSTREE_GRUB2_EXEC=/usr/bin/dummy-mkconfig ostree admin --sysroot="${sysroot}" --os="${stateroot}" deploy "${ref}"
if [ "${no_undeploy}" = 0 ]; then
    env OSTREE_DEBUG_GRUB2=1 OSTREE_GRUB2_EXEC=/usr/bin/dummy-mkconfig ostree admin --sysroot="${sysroot}" undeploy 1
fi
# EVEN MORE tremendous hackery for old systems that use grub2-mkconfig or zipl
if [ "${bootloader}" != "none" ]; then
    # shellcheck disable=SC2010
    deploydir=$(ls -d ${sysroot}/ostree/deploy/*/deploy/* | grep -v '\.origin' | head -1)
    mount -t proc /proc "${deploydir}/proc"
    mount -t sysfs /sys "${deploydir}/sys"
    mount -t devtmpfs devtmpfs "${deploydir}/dev"
    mount -t tmpfs tmpfs "${deploydir}/var"
    mount --bind "${sysroot}" "${deploydir}"/sysroot
    mount -M "${sysroot}/boot" "${deploydir}"/boot
    case "${bootloader}" in
        unset) chroot "${deploydir}" env GRUB_DISABLE_OS_PROBER=true grub2-mkconfig -o /boot/loader/grub.cfg ;;
        zipl) chroot "${deploydir}" zipl ;;
        *) echo "Unhandled bootloader: ${bootloader}" 1>&2; exit 1 ;;
    esac
fi
if [ "${bootloader}" = "zipl" ]; then
    # Set it back now
    sed -i -e 's,bootloader=none,bootloader=zipl,' "${sysroot}"/ostree/repo/config
fi
umount -R "${sysroot}"

